package Q5;
/*
重写线程运行的方法，使得服务器能够实现多人同时在线
 */
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread implements Runnable {

    private User client;
    private ArrayList<User> Client_list;

    public ServerThread(User client, ArrayList<User> client_list) {
        this.client = client;
        Client_list = client_list;
    }

    @Override
    public void run() {
        ObjectInputStream receive = null;
//        ObjectOutputStream back_message = null;
        try {
            receive = client.getReceive();
//            back_message = client.getSend();
            while (true){
                Message message = (Message) receive.readObject();
                System.out.println("服务器已收到客户端 "+client.getName()+" 发送过来的消息: "+ message.getContent());
                System.out.println("服务器已收到客户端 "+client.getName()+" 发送过来的文件为: " + message.getFile());
                sendToAllClient(message);
                System.out.println("已向所有在线客户发送消息");
                if(message.getContent().equalsIgnoreCase("Bye")){
                    System.out.println("客户端 "+ client.getName() + "已下线");
                    removeUser(client);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(null != receive){
                try {
                    receive.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            if(null != client){
//                try {
//                    client.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        }

        public void sendToAllClient(Message message){
            for(User user: Client_list){
                ObjectOutputStream back_message = user.getSend();
                try {
                    back_message.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void removeUser(User user){
                    Client_list.remove(user);
        }
    }

